<template>
  <div class="update-gender">
    <van-picker
      title="标题"
      show-toolbar
      :columns="columns"
      :default-index="localGender"
      @confirm="onConfirm"
      @cancel="$emit('close')"
      @change="onChange"
    />
  </div>
</template>

<script>
import { updateUserProfile } from "@/api/user";
export default {
  name: "UpdateGender",
  props: {
    value: {
      type: Number,
      required: true,
    },
  },
  data() {
    return {
      localGender: this.value,
      columns: ["男", "女"],
    };
  },
  methods: {
    onChange(picker, value, index) {
      this.localGender = index;
    },
    async onConfirm() {
      // 无变更，退出弹层
      if(this.localGender === this.value) {
        return this.$emit('close')
      }
      this.$toast.loading({
        message: '保存中...',
        forbidClick: false,
        duration: 0
      })
      try {
        await updateUserProfile({
          gender: this.localGender,
        });
        this.$toast.success('更新成功')
        this.$emit("input", this.localGender);
        this.$emit("close");
      } catch (err) {
        this.$toast.fail('更新失败')
      }
    },
  },
};
</script>

<style>
</style>